<?php

namespace app\api\controller;

use ba\Tree;
use think\facade\Cache;
use think\facade\Session;
use Throwable;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Config;
use app\common\controller\Frontend;

class Index extends Frontend
{
    protected array $noNeedLogin = ['index', 'isPassword', 'login', 'logout', 'addTel', 'send'];
    protected array $sendTime = [8, 20];

    protected string $key = 'TUZm2KcDDsoetYZV3KBZih';


    public function initialize(): void
    {
        parent::initialize();
    }


    public array $expire = [
        80, 170, 340, 520
    ];






    public function send(){

        $timestamp = time();

        $d = date('H', $timestamp);
        if($d < $this->sendTime[0] || $d >= $this->sendTime[1]) die('该时间段不执行任务');


        $where = [
            ['expire_time', '<', $timestamp]
        ];
        $result = db::name('tel')->whereNull('last_send_time')->where($where)->limit(1)->select()->toArray();
        if(empty($result)){
            echo '没有过期任务';
            die;
        }



        foreach($result as $val){


            $url = "https://api.day.app/{$this->key}/{$val['tel']}?sound=tiptoes";


            $content = file_get_contents($url);

//            print_r($content);die;

            $result = json_decode($content, true);
            if ($result) {


                if($result['code'] == 200){
//                    echo 1;die;
                    db::name('tel')->where(['id' => $val['id']])->update([
                        'last_send_time' => $timestamp,
                        'update_time' => $timestamp
                    ]);
                }else{
                    //请求异常
                    echo '推送失败: ' . $val['tel'] . "\n";
                }

//                print_r($result);

            } else {
                //请求异常
                echo '发起推送请求失败: ' . $val['tel'] . "\n";
            }
        }







        die;
//        db::name('tel')->where(['id' => $val['id']])->update([
//            'last_send_time' => $timestamp,
//            'update_time' => $timestamp
//        ]);g


        print_r($result);die;
    }





    public function addTel(){
        $params = $this->request->param();
        if(empty($params['expire_time'])) $this->error('请输入到期天数');
        if(empty($params['tel'])) $this->error('请输入手机号码');
        $tel = explode("\n", $params['tel']);
        $tel = array_unique($tel);
        $tel = array_filter($tel);
        if(empty($tel)) $this->error('请输入手机号码');

        $insert = [];
        $timestamp = time();
        $expire_time = $timestamp + (86400 * $params['expire_time']);
        foreach($tel as $val){
            $insert[] = [
                'tel' => $val,
                'expire_time' => $expire_time,
                'create_time' => $timestamp
            ];
        }
        $res = Db::name('tel')->insertAll($insert);
        if($res){
            $number = db::name('tel')->whereNull('last_send_time')->count();
            $this->success('', ['code' => 200, 'number' => $number]);
        }else{
            $this->error();
        }

    }

    public function login(){
        $params = $this->request->param();
        if(empty($params['password'])) $this->error('请输入密码');

        if($params['password'] != '123456'){
            $this->error('密码错误');
        }
        Cookie::set('isPassword', 1);
        $this->success();

    }

    public function logout(){
        Cookie::delete('isPassword');
        $this->success();
    }


    public function isPassword(){
//        var_dump(session::get('isPassword'));die;
        $cache = Cookie::has('isPassword');

        $number = db::name('tel')->whereNull('last_send_time')->count();

        $this->success('', [
            'cache' => $cache,
            'number' => $number,
            'expire' => $this->expire
        ]);
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(): void
    {
        $menus = [];
        if ($this->auth->isLogin()) {
            $rules     = [];
            $userMenus = $this->auth->getMenus();

            // 首页加载的规则，验权，但过滤掉会员中心菜单
            foreach ($userMenus as $item) {
                if ($item['type'] == 'menu_dir') {
                    $menus[] = $item;
                } else if ($item['type'] != 'menu') {
                    $rules[] = $item;
                }
            }
            $rules = array_values($rules);
        } else {
            // 若是从前台会员中心内发出的请求，要求必须登录，否则会员中心异常
            $requiredLogin = $this->request->get('requiredLogin/b', false);
            if ($requiredLogin) {
                $token = $this->request->server('HTTP_BA_USER_TOKEN', $this->request->request('ba-user-token', Cookie::get('ba-user-token') ?: false));

                // 若过期可触发过期判定
                $this->auth->init($token);

                // 未过期或无token，直接要求登录
                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }

            $rules = Db::name('user_rule')
                ->where('status', '1')
                ->where('no_login_valid', 1)
                ->where('type', 'in', ['route', 'nav', 'button'])
                ->order('weigh', 'desc')
                ->select()
                ->toArray();
            $rules = Tree::instance()->assembleChild($rules);
        }

        $this->success('', [
            'site'             => [
                'siteName'     => get_sys_config('site_name'),
                'recordNumber' => get_sys_config('record_number'),
                'version'      => get_sys_config('version'),
                'cdnUrl'       => full_url(),
                'upload'       => get_upload_config(),
            ],
            'openMemberCenter' => Config::get('buildadmin.open_member_center'),
            'userInfo'         => $this->auth->getUserInfo(),
            'rules'            => $rules,
            'menus'            => $menus,
        ]);
    }
}